import moment from 'moment';
import store from '../store/store';
export default {
    install(Vue) {
        var getBarSeries=function(echartsItem,list){
            var serises=[];
            if(list!=null&&list.length>0)
            {
                for(var i =0;i<list.length;i++)
                {
                    serises.push({
                        "name":echartsItem[i],
                        "type":'bar',
                        "data":list[i],
                        "markPoint":{
                            "data" : [
                                {
                                    "type" : 'max', "name": '最大值'
                                },{
                                    "type" : 'min', "name": '最小值'
                                }
                            ]
                        }
                    });
                }
            }
            return serises;
        };
        //获取地图定位数据
        var convertData = function (GeoData,data) {
            var res = [];
            var GeoJson=JSON.parse(GeoData);
            for (var i = 0; i < data.length; i++) {
                var geoCoord = GeoJson[data[i].name];
                if (geoCoord) {
                    res.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value)
                    });
                }
                
            }
            return res;
        };
        var getMapSeries=function(GeoData,mapType,echartsItem,list){
            var series=[];
            console.log(list)
            if(list!=null&&list.length>0)
            {
                for(var i=0;i<list.length;i++)
                {
                    console.log(list[i])
                    series.push({
                        name:echartsItem[i],
                        type: 'map',
                        roam: true,//地图是否随鼠标滑动而放大缩小
                        mapType: mapType,
                        aspectScale: 0.9,
                        border:0,
                        // showEffectOn: 'render',
                        // rippleEffect: {
                        //     brushType: 'stroke'
                        // },
                        hoverAnimation: true,
                        label: {
                            normal: {
                                show: true,//显示省份标签
                                formatter: '{b}',
                                textStyle:{color:"#c71585"}//省份标签字体颜色
                            },    
                            emphasis: {//对应的鼠标悬浮效果
                                show: true,
                                textStyle:{color:"#800080"}
                            } 
                        },
                        itemStyle: {
                            normal: {
                                borderWidth: 0.5,//区域边框宽度
                                borderColor: '#009fe8',//区域边框颜色
                                areaColor:"#ffefd5",//区域颜色
                            },
                            emphasis: {
                                // borderWidth: .5,
                                borderColor: '#4b0082',
                                areaColor:"#ffdead",
                            }
                        },
                        data:list[i],
                    });
                    series.push({
                        name:echartsItem[i],
                        type: 'effectScatter',
                        show:false,
                        coordinateSystem: 'geo',
                        roam: true,//地图是否随鼠标滑动而放大缩小
                        mapType: mapType,
                        // aspectScale: 1,
                        // border:0,
                        symbol:'pin',
                        symbolSize:40,
                        // large:true,
                        
                        // showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke',
                            color:'#FFF'
                        },
                        hoverAnimation: true,
                        label: {
                            show:false
                        },
                        itemStyle: {
                            normal: {
                                shadowBlur: 20,
                                borderWidth: 0.5,//区域边框宽度
                                color:'#000',
                                // borderColor: '#009fe8',//区域边框颜色
                                areaColor:"#ffefd5",//区域颜色
                            },
                            emphasis: {
                                // borderWidth: .5,
                                borderColor: '#4b0082',
                                areaColor:"#ffdead",
                            }
                        },
                        data:convertData(GeoData,list[i].sort(function(a,b){return b.value-a.value;}).slice(0,4)),
                        zlevel: 1
                        
                    });
                }
            }
            return series;
        };
        
        Vue.prototype.GetGeoData=function(AreaCode){
            var areaList=this.getAllAreaList(AreaCode);
            var GeoData="";
            if(areaList!=null)
            {
                GeoData="{";
                for(var i=0;i<areaList.length;i++)
                {
                    if(i<areaList.length-1){
                        GeoData+="\""+areaList[i].FullName+"\":"+areaList[i].Coord+",";
                    }
                    else{
                        GeoData+="\""+areaList[i].FullName+"\":"+areaList[i].Coord;
                    }
                }
                GeoData+="}"; 
            }
            return GeoData;
        },
        //获取柱状图配置文件
        Vue.prototype.GetBarOption=function(TableName,AreaData,echartsItem,list){
            var Option={
                title: {
                    text: TableName,
                    top:0,
                    left:'center',
                    textStyle:{
                        color:'#3C4251',
                        fontWeight:'bold',
                        fontSize:20
                    }
                },
                tooltip : {
                    trigger: 'axis',
                    axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                        type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    label: {
                        show: true,
                        backgroundColor: '#333'
                    }
                },
                //工具箱
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'left',
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    feature: {
                        magicType: {type: ['line', 'bar']},
                        dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                calculable : true,
                //切换项
                legend: {
                    orient:'vertical',
                    left:'right',
                    data:echartsItem
                },
                xAxis : [
                    {
                        // position:'top',//x轴位置
                        name:'X',
                        type : 'category',
                        data : AreaData,
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        },
                        axisLabel: {  
                            interval:0,  
                            rotate:-15  
                        }
                    },
                    
                ],
                yAxis : [
                    {
                        name:'Y',
                        nameGap:10,
                        type : 'value',  
                    }
                ],
                series : getBarSeries(echartsItem,list)
            };
            return Option;
        },
        Vue.prototype.GetMapOption=function(TableName,GeoData,mapType,echartsItem,list){
            var option = {
                title: {text: TableName,top:0,left:'center',textStyle:{
                    color:'#3C4251',
                    fontWeight:'bold',
                    fontSize:20
                }},
                // backgroundColor:'#F8F8F9',
                tooltip: {
                    backgroundColor:"#ff7f50",//提示标签背景颜色
                    textStyle:{color:"#fff"} //提示标签字体颜色
                },
                legend: {
                    orient:'vertical',
                    left:'right',
                    data:echartsItem,//数据集
                    selectedMode: 'single',
                },
                geo: {
                    map:  mapType,
                    aspectScale: 0.9,
                    label: {
                        emphasis: {
                            // show: false
                        }
                    },
                    roam: true,
                },
                toolbox: {
                    show: true,
                    orient: 'vertical',
                    left: 'left',
                    top: 'top',
                    itemSize:20,
                    itemGap:30,
                    feature: {
                        dataView: {readOnly: false},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                visualMap: {
                    show:true,
                    // type: 'continuous',
                    type:'piecewise', 
                    splitNumber:20,
                    pieces:[
                        {min:0,max:5},
                        {min:0,max:50},
                        {min:0,max:100},
                        {min:0,max:200},
                        {min:0,max:500},
                        {min:0,max:1000},
                        {min:0,max:3000},
                        {min:0,max:5000},
                        {min:0,max:10000},
                        {min:0,max:50000},
                        {min:0,max:100000},
                        {min:0,max:150000},
                        {min:0,max:250000},
                        {min:0,max:500000},
                        {min:0,max:50000000},
                        {min:0,max:500000000},
                        {min:0,max:2500000000},
                        {min:0,max:5000000000},
                        {min:0,max:10000000000},
                    ],
                    calculable : true,
                    min: 0,
                    max: '500000',
                    text:['最大值','最小值'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['white','lightskyblue','yellow','#FFCC00','orange','orangered'],
                        // symbolSize: [30, 100]
                    },
                    bottom:'bottom'
                },
                series:getMapSeries(GeoData,mapType,echartsItem,list)
            };
            return option;
        },
        //获取年间对比折线图配置
        Vue.prototype.getLineOption = function(PropDataList,propIndex,propName){
            let lineDatas = [];
            let Legends = [];
            let yearList = this.getAllYears();
            for(var i=0;i<PropDataList.length;i++){
                let Item = PropDataList[i];
                let model = {
                    name:Item[propIndex].AreaName,
                    type:'line',
                    // markPoint: {
                    //     data: [
                    //         {type: 'max', name: '最大值'},
                    //         {type: 'min', name: '最小值'}
                    //     ]
                    // },
                    // markLine: {
                    //     data: [
                    //         {type: 'average', name: '平均值'}
                    //     ]
                    // },
                    data:Item[propIndex].allYearDataList,
                };
                Legends.push(Item[propIndex].AreaName)
                lineDatas.push(model)
            }
            let lineOption = {
                color:['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83','#7787c5','#b2c5ff','#e0e0f8','#9bb120','#c3db51','#e08031','#c7ceb2','#199475','#0b6e48','#044d22','#aab8a3'],
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c}'
                },
                legend: {
                    data:Legends
                },
                grid: {
                    left: '3%',
                    right: '5%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    name: '年份',
                    splitLine: {show: false},
                    data: yearList,
                },
                yAxis: {
                    type: 'value',
                    name: propName
                },
                series: lineDatas
            };
            return lineOption;
        },
        //获取所有年份
        Vue.prototype.getAllYears=function() {
            let DictYearList=this.GetGroupDict("ReportYear");
            console.log("ttt")
            console.log(DictYearList)
            let yearList = [];
            for(var i = 0;i < DictYearList.length;i++){
                yearList.push(DictYearList[i].DictValue)
            }
           return yearList;
        },
        //根据用户当前地区编码,获取地区信息
        Vue.prototype.getAllAreaList=function(AreaCode) {
            var areaCode = AreaCode;
            var areaList=[];
            if (areaCode != '530000000000' && areaCode != null) {
                var item = this.GetlocaStorage("areatreelist")[0];
                for (var i = 0; i < item.children.length; i++) {
                    if (item.children[i].value == areaCode) {
                        areaList.push(item.children[i]);
                    }
                }
            } else {

                areaList = this.GetlocaStorage("areatreelist");
            }
            return areaList[0].children;
        },
        Vue.directive('omg-operation', function (el, binding) {
            var keyVal = binding.value.op;
            var actions = store.state.ActionInfo.list;
            var account = store.state.ActionInfo.Account;
            var has = false;
            if (account != 'admin') {
                for (var i = 0; i < actions.length; i++) {
                    if (actions[i].ActionCode == keyVal) {
                        has = true;
                    }
                }
                if (!has) {
                    el.style.display = "none";
                }
            }
            el.style.display = "none";
        }),
            Vue.directive('omg-set-menu-height', function (el, binding) {
                var height = 0;
                window.onresize = function () {
                    height = window.innerHeight * 1 - 110;
                    el.style.height = height + 'px';
                }
                height = window.innerHeight * 1 - 110;
                el.style.height = height + 'px';
            }),
            Vue.filter("omgConvStatus", function (val) {
                if (val * 1 === 1) {
                    return '启用';
                } else {
                    return '停用';
                }
            }),
            Vue.filter("moment", function (value, formatString) {
                if (value == null) {
                    return "";
                } else {
                    formatString = formatString || 'YYYY-MM-DD HH:mm:ss';
                    return moment(value).format(formatString);
                }
            }),
            Vue.filter("omgConvDict", function (val, groupCode) {
                var result = "";
                var dictlist = JSON.parse(window.sessionStorage.getItem("dictlist"));
                if (dictlist.length != 0) {
                    for (var i = 0; i < dictlist.length; i++) {
                        if (dictlist[i].GroupCode == groupCode && dictlist[i].DictValue == val) {
                            result = dictlist[i].DictText;
                        }
                    }
                }
                return result;
            }),
            Vue.filter("omgAreaName", function (val) {
                var result = "";
                var list = JSON.parse(window.sessionStorage.getItem("arealist"));
                if (list.length != 0) {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].Code == val) {
                            result = list[i].Name;
                        }
                    }
                }
                return result;
            }),
            Vue.prototype.SetlocaStorage = function (strkey, obj) {
                if (window.sessionStorage) {
                    window.sessionStorage.setItem(strkey, JSON.stringify(obj));
                }
                else {
                    alert("浏览暂不支持sessionStorage")
                }
            },
            Vue.prototype.GetlocaStorage = function (strkey) {
                if (window.sessionStorage) {
                    return JSON.parse(window.sessionStorage.getItem(strkey));
                }
                else {
                    alert("浏览暂不支持sessionStorage")
                }
            },
            Vue.prototype.GetGroupDict = function (groupCode) {
                //需要传入分组代码groupCode
                var dictlist = JSON.parse(window.sessionStorage.getItem("dictlist"));
                var resultlist = [];
                if (dictlist.length != 0) {
                    for (var i = 0; i < dictlist.length; i++) {
                        if (dictlist[i].GroupCode == groupCode) {
                            resultlist.push(dictlist[i]);
                        }
                    }
                }
                return resultlist;
            },
            Vue.prototype.GetArea = function (parentCode) {
                //需要传入分组代码groupCode
                var list = JSON.parse(window.sessionStorage.getItem("arealist"));
                var resultlist = [];
                if (list.length != 0) {
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].ParentCode == parentCode) {
                            resultlist.push(list[i]);
                        }
                    }
                }
                return resultlist;
            },
            Vue.prototype.FormatBigNum = function(num){
                if(num){
                    let numStr = num.toString();
                    if(numStr.indexOf(".") != -1){
                        let index = numStr.indexOf(".");
                        let IntStr = numStr.substring(0,index);
                        let floatStr = numStr.slice(index);
                        return IntStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",")+floatStr;
                    }
                    else{
                        return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                    }
                }
            },
            Number.prototype.toFixed = function(s){
                var that = this,changenum,index;
                // 负数
                if(this < 0){
                    that = -that;
                }
                changenum = (parseInt(that * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
                index = changenum.indexOf(".");
                if (index < 0 && s > 0) {
                    changenum = changenum + ".";
                    for (var i = 0; i < s; i++) {
                        changenum = changenum + "0";
                    }
                } else {
                    index = changenum.length - index;
                    for (var i = 0; i < (s - index) + 1; i++) {
                        changenum = changenum + "0";
                    }
                }
                if(this<0){
                    return changenum*(-1); 
                }else{
                    return changenum * 1; 
                }     
            },
            //只获取儿系地区列表，即州级只能获取下属县级列表，省级只获取州级列表而不获取县级
            Vue.prototype.getChildAreaList= function(userAreaCode){
                var areaCode = userAreaCode;
                var areaList=[];
                var templist = [];
                var areaEntity = new Object();
                areaEntity.value=areaCode;
                areaEntity.children=[];
                if (areaCode != '530000000000' && areaCode != null) {
                    var item = this.GetlocaStorage("areatreelist")[0];
                    areaEntity.label="全州（市）";
                    for (var i = 0; i < item.children.length; i++) {
                        if (item.children[i].value == areaCode) {
                            areaList = item.children[i];
                        }
                    }
                } else {
                    areaEntity.label="全省";
                    areaList = this.GetlocaStorage("areatreelist")[0];
                }
                templist.push(areaEntity);
                if(areaList.children)
                templist = templist.concat(areaList.children);
                return templist;
            }

            
    }
}